package com.airnews.ticket.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.EncodingUtils;

import android.content.Context;

import com.airnews.ticket.model.Addr;

public class AddrUtil {
	private List<Addr> alist = new ArrayList<Addr>();
	private Context context;

	public AddrUtil(Context context) {
		this.context = context;
	}

	public Addr getCityByCode(String code) {
		if (alist.size() == 0) {
			init();
		}
		for (int i = 0; i < alist.size(); i++) {
			if (alist.get(i).getCode().equals(code)) {
				return alist.get(i);
			}
		}
		return null;
	}

	public String getCodeByCity(String city) {
		if (alist.size() == 0) {
			init();
		}
		for (int i = 0; i < alist.size(); i++) {
			if (alist.get(i).getCity().equals(city)) {
				return alist.get(i).getCode();
			}
		}
		return "";
	}
	public String getEnglishNameByCode(String code) {
		if (alist.size() == 0) {
			init();
		}
		for (int i = 0; i < alist.size(); i++) {
			if (alist.get(i).getCode().equals(code)) {
				return alist.get(i).getEnglish();
			}
		}
		return null;
	}
	public void init() {
		InputStream in = null;
		try {
			byte[] b = new byte[12000];
			in = context.getAssets().open("addr.data");
			int length = in.read(b, 0, 12000);
			String str = EncodingUtils.getString(b, 0, length, "UTF-8");
			String[] strs = str.split("\r\n");
			for (int i = 0; i < strs.length; i++) {
				String[] ss = strs[i].split("\t");
				Addr addr = new Addr();
				addr.setAirName(ss[0]);
				addr.setCode(ss[1]);
				addr.setEnglish(ss[2]);
				addr.setCity(ss[3]);
				if(ss[3].contains("\r")){
					addr.setCity(ss[3].replace("\r", ""));
				}
			
				alist.add(addr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
